package bobo;


import com.github.javaparser.Position;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.symbolsolver.JavaSymbolSolver;
import com.github.javaparser.resolution.UnsolvedSymbolException;

import javassist.compiler.ast.MethodDecl;

import com.github.javaparser.Range;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.metamodel.NodeMetaModel;
import com.github.javaparser.metamodel.PropertyMetaModel;

//import org.w3c.dom.ranges.Range;

import java.util.List;
import java.util.Optional;

import static com.github.javaparser.utils.Utils.assertNotNull;
import static java.util.stream.Collectors.toList;

import java.nio.charset.StandardCharsets;

/**
 * Outputs an XML file containing the AST meant for inspecting it.
 */
public class MyXmlPrinter {
    private final boolean outputNodeType;

    public MyXmlPrinter(boolean outputNodeType) {
        this.outputNodeType = outputNodeType;
    }

    public String output(Node node) {
        StringBuilder output = new StringBuilder();
        output(node, "root", 0, output);
        return output.toString();
    }

    public String convert_xmlstring(String s_value) {
        s_value = s_value.replaceAll("<", "&lt;");
        s_value = s_value.replaceAll(">", "&gt;");
        s_value = s_value.replaceAll("&", "&amp;");
        s_value = s_value.replaceAll("\"", "&quot;");
        s_value = s_value.replaceAll("\'", "&apos;");
        byte[] temp = s_value.getBytes(StandardCharsets.UTF_8);
        s_value = new String(temp, StandardCharsets.UTF_8);

        return s_value;
    }

    public void output(Node node, String name, int level, StringBuilder builder) {
        assertNotNull(node);
        NodeMetaModel metaModel = node.getMetaModel();
        List<PropertyMetaModel> allPropertyMetaModels = metaModel.getAllPropertyMetaModels();
        List<PropertyMetaModel> attributes = allPropertyMetaModels.stream().filter(PropertyMetaModel::isAttribute).filter(PropertyMetaModel::isSingular).collect(toList());
        List<PropertyMetaModel> subNodes = allPropertyMetaModels.stream().filter(PropertyMetaModel::isNode).filter(PropertyMetaModel::isSingular).collect(toList());
        List<PropertyMetaModel> subLists = allPropertyMetaModels.stream().filter(PropertyMetaModel::isNodeList).collect(toList());

        builder.append("<").append(name);
        if (outputNodeType) {
            builder.append(attribute("element_type", metaModel.getTypeName()));
        }

        if (node instanceof MethodCallExpr ) {
            String call_usr = "";
            MethodCallExpr mc = (MethodCallExpr)node;

            try{
                Optional<MethodDeclaration> method_decl = mc.resolve().toAst();
                if (method_decl.isPresent()) {
                    MethodDeclaration md = method_decl.get();
                    call_usr = md.getDeclarationAsString();
                    //System.out.println(md.getDeclarationAsString());
                }
            } catch (UnsolvedSymbolException exc) {
                System.out.println("unknow method call, " + mc.getNameAsString());
            } catch (java.lang.RuntimeException exc) {
                System.out.println("unknow method call, " + mc.getNameAsString());
            }
           

            
            builder.append(attribute("call_usr", convert_xmlstring(call_usr)));
        }

        if (node instanceof MethodDeclaration) {
            MethodDeclaration md = (MethodDeclaration)node;
            builder.append(attribute("usr", convert_xmlstring(md.getDeclarationAsString() )));
        }

        for (PropertyMetaModel attributeMetaModel : attributes) {
            String s_value = attributeMetaModel.getValue(node).toString();
            
            builder.append(attribute(attributeMetaModel.getName(), convert_xmlstring(s_value)));
        }

        Optional<Range> range = node.getRange();
        if (range.isEmpty() == false) {
            Range r = range.get();
            Position pos_s = r.begin;
            Position pos_e = r.end;
            builder.append(attribute("start_line", String.valueOf(pos_s.line)));
            builder.append(attribute("start_col", String.valueOf(pos_s.column)));
            builder.append(attribute("end_line", String.valueOf(pos_e.line)));
            builder.append(attribute("end_col", String.valueOf(pos_e.column)));
        }

        builder.append(">");

        for (PropertyMetaModel subNodeMetaModel : subNodes) {
            Node value = (Node) subNodeMetaModel.getValue(node);
            if (value != null) {
                output(value, subNodeMetaModel.getName(), level + 1, builder);
            }
        }

        for (PropertyMetaModel subListMetaModel : subLists) {
            NodeList<? extends Node> subList = (NodeList<? extends Node>) subListMetaModel.getValue(node);
            if (subList != null && !subList.isEmpty()) {
                String listName = subListMetaModel.getName();
                builder.append("<").append(listName).append(">");
                String singular = listName.substring(0, listName.length() - 1);
                for (Node subListNode : subList) {
                    output(subListNode, singular, level + 1, builder);
                }
                builder.append(close(listName));
            }
        }
        builder.append(close(name));
    }

    private static String close(String name) {
        return "</" + name + ">";
    }

    private static String attribute(String name, String value) {
        return " " + name + "='" + value + "'";
    }

    public static void print(Node node) {
        System.out.println(new MyXmlPrinter(true).output(node));
    }
}

